package com.ruoyi.rva.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.rva.domain.RvaMap;
import com.ruoyi.rva.service.IRvaMetaService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 元数据管理
 * 
 * @author jiaodacailei
 * @date 2021-07-27
 */
@RestController
@RequestMapping
public class RvaMetaController extends BaseController
{
    @Autowired
    private IRvaMetaService metaService;

    /**
     * 在对象1列表上点击创建CRUD
     * @param req
     * @return
     */
    @PostMapping("/rva/meta/crud/create")
    public AjaxResult createCrud(@RequestBody Map<String, Object> req)
    {
        List<Map> selection = new RvaMap(req).getList("selection");
        metaService.createCrud(selection.get(0).get("l1_rva_object_id").toString());
        return AjaxResult.success();
    }

    private List<String> getCrudId (Map<String, Object> req) {
        RvaMap<String, Object> rvaMap = new RvaMap<>(req);
        List<String> ids = new ArrayList<>();
        rvaMap.getList("selection").forEach(row -> {
            ids.add(((Map<String, Object>)row).get("l1_rva_app_id").toString());
        });
        return ids;
    }

    @PostMapping("/rva/meta/crud/clone")
    public AjaxResult cloneCrud(@RequestBody Map<String, Object> req)
    {
        metaService.cloneApp(getCrudId(req).get(0), false, true);
        return AjaxResult.success();
    }

    @PostMapping("/rva/meta/crud/delete")
    public AjaxResult deleteCrud(@RequestBody Map<String, Object> req)
    {
        metaService.deleteApp(getCrudId(req));
        return AjaxResult.success();
    }

    @Autowired
    private ISysConfigService sysConfigService;

    @PostMapping("/rva/meta/crud/createMenu")
    public AjaxResult createMenu(@RequestBody Map<String, Object> req)
    {
        String menuId = sysConfigService.selectConfigByKey("rva.menu.id");
        List<Map> selection = new RvaMap(req).getList("selection");
        metaService.createMenuAndButtons(selection.get(0).get("l1_rva_app_id").toString(), Long.parseLong(menuId),99);
        return AjaxResult.success();
    }
}
